package com.myblog.config.security;

import com.myblog.config.filter.MobileAuthenticationFilter;
import com.myblog.config.security.handle.CustomAuhtenticationFailureHandler;
import com.myblog.config.security.handle.CustomAuhtenticationSuccessHandler;
import com.myblog.service.impl.MobileUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import org.springframework.stereotype.Component;

/**
 * 用于组合其他关于手机登录的组件
 */
@Component
public class MobileAuthenticationConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {


    @Autowired
    CustomAuhtenticationFailureHandler customAuhtenticationFailureHandler;

    @Autowired
    CustomAuhtenticationSuccessHandler customAuhtenticationSuccessHandler;

    @Autowired
    MobileUserDetailService mobileUserDetailService;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        MobileAuthenticationFilter mobileAuthenticationFilter =new MobileAuthenticationFilter();
        //指定记住我功能
        mobileAuthenticationFilter.setRememberMeServices(http.getSharedObject(RememberMeServices.class));
        //指定同样手机号登录时 也就session重复登录问题
        mobileAuthenticationFilter.setSessionAuthenticationStrategy(http.getSharedObject(SessionAuthenticationStrategy.class));
        //获取容器中已经存在的AuthenticationManager
        mobileAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        //传入成功失败处理器
        mobileAuthenticationFilter.setAuthenticationSuccessHandler(customAuhtenticationSuccessHandler);
        mobileAuthenticationFilter.setAuthenticationFailureHandler(customAuhtenticationFailureHandler);
        //构建一个mobileAuthenticationProvider实例接受mobileUserDetailService通过手机号查询用户信息
        MobileAuthenticationProvider mobileAuthenticationProvider=new MobileAuthenticationProvider();
        mobileAuthenticationProvider.setUserDetailsService(mobileUserDetailService);
        //将额外的mobileAuthenticationProvider 绑定到HttpSecurity上 并绑定到用户名和密码认证过滤器之后
        http.authenticationProvider(mobileAuthenticationProvider).addFilterAfter(mobileAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        super.configure(http);
    }
}
